#include "Race.h"
#include "Player.h"
#include "Track.h"
#include "DebugTracer.h"

extern DebugTracer _DEBUGTRACER;
Race::Race()
{
    m_track = NULL;
    m_track = new Track();
    m_elapsedTime = 0;
    m_started = false;

}

Race::~Race()
{
    //dtor
}

void Race::Update(float timedelta)
{
    if(!m_started)
    {
    }
    else
    {
        m_elapsedTime += timedelta;
        m_track->Update(timedelta);
        BOOST_FOREACH(Player* player,m_playerList)
            player->Update(timedelta);
    }
}

void Race::AddPlayer(Player* player)
{
    m_playerList.push_back(player);
}

void Race::SelectTrack(Track* track)
{
    m_track = track;
}

Player* Race::GetPlayer(const std::string& name)
{
    BOOST_FOREACH(Player* player, m_playerList)
    {
        if(player->GetName() == name)
            return player;
    }
    return NULL;
}

void Race::Start()
{
    m_started = false;

    //initializing the position of each player randomly
    static boost::mt19937 gen;
    boost::uniform_int<> dist(0,m_playerList.size()-1);
    boost::variate_generator<boost::mt19937&,boost::uniform_int<> > random(gen,dist);


    for(unsigned int i = 0; i < m_playerList.size(); i++)
    {
        int choosen_one = random();
        Player* player = m_playerList.at(choosen_one);
        player->SetRank(0);
        m_playerList.erase(m_playerList.begin() + choosen_one);
        m_playerList.insert(m_playerList.begin(),player);
    }

    unsigned int node_counter = m_track->GetVectorList().size() - 1;
    for(unsigned int i = 0; i < m_playerList.size(); i++)
    {
        m_playerList[i]->SetRank(i);
		std::cout << "Player Jet : " << m_playerList[i]->GetJet()->GetAuthor() << std::endl;
        m_playerList[i]->GetJet()->InitNodes(i);
        node_counter -= (int)Track::NODES_PER_METER;
    }

}
